import React from  'react'
import { Table,Modal,message,Button,Card,Form ,Input,Tree } from 'antd'
import axios from "../../../axios/axios";
import BaseFilterForm from './../../../components/BaseFilterForm'

import './../../../style/common.less'

const TreeNode = Tree.TreeNode
export default class User extends React.Component{

    state={
        dataSource:[],
        expandedKeys: [],
        autoExpandParent: true,
        checkedKeys: [],
        selectedKeys: [],
        treeData:[],
        isGrantVisible:false,
        roleId:'',
        menuIds:''
    }
    //  --------------------- tree控件配置 start -------------------------
    onExpand = (expandedKeys) => {
        console.log('onExpand', expandedKeys);
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        })
    }
    onCheck = (checkedKeys) => {
        console.log('onCheck----------', checkedKeys);
        this.setState({ checkedKeys });
    }

    onSelect = (selectedKeys, info) => {
        console.log('onSelect----------', info);
        this.setState({ selectedKeys });
    }
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                )
            }
            return <TreeNode {...item} />;
        })
    }
    handGrant=()=>{
        let rows = this.state.selectedRows
        if (rows.length===1){
            // 向后台获取tree数据
            axios.ajax({
                url: '/cloud-long-upms/sysMenu/getAllTreeNode',
                method:'get'
            }).then((res)=>{
                console.log(res.data.treeNodeList)
                if (res.status===200) {
                    this.setState({
                        isGrantVisible:true,
                        roleId:rows[0].id,
                        treeData:res.data.treeNodeList
                    })
                }
            })
        }else {
            Modal.warn({
                title:'提示',
                content:'请选择一行进行授权!'
            })
        }
    }
    grant=()=>{
        console.log(this.state.checkedKeys)
        message.info(`${this.state.checkedKeys}`)
        let menuIds=this.state.checkedKeys.join(',')
        axios.ajax({
            url:'/cloud-long-upms/sysRole/grantMenu',
            method:'post',
            data:{
                params:{
                    roleId:this.state.roleId,
                    menuIds:menuIds
                }
            }
        })
    }
//  --------------------- tree控件配置 end -------------------------
    params = {
        page:1,
        limit:5
    }

    formList = [
        {
            type:'INPUT',
            label:'角色名称',
            field:'name',
            placeholder:'模糊查询角色名'
        }
    ]
    componentWillMount(){
        this.filterSubmit()
    }

    handleOperator = (type)=> {
        let rows = this.state.selectedRows
        if(type ==='create'){
            this.setState({
                title:'创建角色',
                isVisible:true,
                type
            })
        }else if(type==="edit" || type==='detail'){
            if (!rows || rows.length>1){
                Modal.warn({
                    title:'警告',
                    content:'只能选中一行进行编辑!'
                })
                return
            }
            this.setState({
                title:type==='edit'?'编辑用户':'查看详情',
                isVisible:true,
                roleInfo:rows[0],
                type
            })

        }else if(type ==='delete'){
            // 先进行过滤
            if ( !rows || rows.length ===0){
                Modal.warn({
                    title:'警告',
                    content:'需要至少先选中一行!'
                })
                return
            }
            // 获取ids
            let idList = []
            let roleNameList=[]
            rows.map((item) => {
                idList.push(item.id)
                roleNameList.push(item.name)
                return item
            })
            let ids=idList.join(",")
            // 进行删除
            Modal.confirm({
                title:`确定要删除:${roleNameList.join(',')}角色`,
                okText:'确定',
                onOk:() => {
                    axios.ajax({
                        url:'/cloud-long-upms/sysRole/deleteBatch',
                        method:'delete',
                        data:{
                            params:{
                                ids:ids
                            }
                        }
                    }).then((res)=>{
                        if (res.status===200) {
                            this.setState({
                                isVisible:false
                            })
                            message.info(`${res.message}`)
                            this.requestList()
                        }
                    })
                },
                onCancel:() => {
                    message.info("取消批量删除!")
                },
                cancelText:'取消'
            })
        }
    }

    handleSubmit =()=>{
        let type = this.state.type
        let data =  this.roleForm.props.form.getFieldsValue()
        if (type === 'edit'){
            data.id = this.state.selectedRows[0].id
        }
        axios.ajax({
            url:type === 'create'? '/cloud-long-upms/sysRole/add':'/cloud-long-upms/sysRole/update',
            method:type === 'create'? 'post':'put',
            data:{
                params:{
                    ...data
                }
            }
        }).then((res)=>{
            if(res.status ===200){
                this.setState({
                    isVisible:false
                })
                message.info(type === 'create'? '添加一笔数据成功!':'一笔数据修改完成!')
                this.requestList();
            }
        })
    }

    //查询提交
    filterSubmit = (fieldsValue)=>{
        this.params =Object.assign(this.params, fieldsValue)
        this.requestList()

    }

    requestList = () => {
        axios.requestList(this,'/cloud-long-upms/sysRole/page','get',this.params)
    }

    render(){
        const selectedRowKeys = this.state.selectedRowKeys
        const rowCheckSelection = {
            type: 'checkbox',
            selectedRowKeys,
            // 单选框也可以用onChange onRow 适合单选
            onChange:(selectedRowKeys,selectedRows)=>{
                this.setState({
                    selectedRowKeys,
                    selectedRows
                })
            }
        }
        const columns=[
            {
                title:'id',
                dataIndex:'id',
                width:340
            },
            {
                title: '角色',
                dataIndex: 'name'
            },
            {
                title: '父角色',
                dataIndex: 'pid'
            },
            {
                title: '层级',
                dataIndex: 'level'
            },
            {
                title: '描述 ',
                dataIndex: 'remark'
            }
        ]
        return (
            <div>
                <Card>
                    <BaseFilterForm formList={this.formList} filterSubmit={ this.filterSubmit } />
                </Card>

                <Card style={{marginTop:10}}>
                    <Button type="danger" icon="delete" onClick={()=>this.handleOperator('delete')}>删除</Button>
                    <Button icon="plus" onClick={ ()=>this.handleOperator('create') }>增加</Button>
                    <Button icon="edit" onClick={()=>this.handleOperator('edit')}>编辑</Button>
                    <Button icon="setting" onClick={this.handGrant}>授权</Button>
                </Card>

                <Table className="content-wrap"
                       bordered
                       rowSelection={rowCheckSelection}
                       columns={columns}
                       dataSource={this.state.dataSource}
                       pagination={this.state.pagination}
                />

                <Modal
                    title={ this.state.title }
                    visible={ this.state.isVisible }
                    onOk={ this.handleSubmit }
                    okText="确定"
                    width={ 600 }
                    onCancel={ () =>{
                        this.roleForm.props.form.resetFields()
                        this.setState({
                            isVisible:false,
                            roleInfo:''
                        })
                    }}
                    cancelText="取消"
                >
                    <RoleForm roleInfo ={ this.state.roleInfo } type={ this.state.type } wrappedComponentRef={(inst) => this.roleForm = inst }/>
                </Modal>
                <Modal
                    title="权限授权"
                    visible={this.state.isGrantVisible}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.grant}
                    onCancel={()=>{
                        this.setState({
                            isGrantVisible:false
                        })
                        message.info('取消权限授权!')
                    }}

                >
                    <div>
                        <Tree
                            showLine
                            checkable
                            onExpand={this.onExpand}
                            expandedKeys={this.state.expandedKeys}
                            autoExpandParent={this.state.autoExpandParent}
                            onCheck={this.onCheck}
                            checkedKeys={this.state.checkedKeys}
                            onSelect={this.onSelect}
                            selectedKeys={this.state.selectedKeys}
                        >
                            {this.renderTreeNodes(this.state.treeData)}
                        </Tree>
                    </div>
                </Modal>
            </div>
        )
    }
}
class RoleForm extends React.Component{

    render(){
        const { getFieldDecorator } =this.props.form
        const roleInfo = this.props.roleInfo || {}
        const type = this.props.type
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 15}
        };
        return (
            <Form layout="horizontal">
                <Form.Item label="角色名" {...formItemLayout}>
                    {
                        roleInfo && type ==='detail' ? roleInfo.name:
                            getFieldDecorator('name',{
                                initialValue:roleInfo.name,
                                rules:[
                                    {
                                        required:true,
                                        message:'角色名不能为空!'
                                    },
                                    {
                                        pattern:/^[a-zA-Z0-9_-]{4,16}$/, // new RegExp('^\\w+$','g')
                                        message:'角色必需为英文字母或数字下划线-!'
                                    }
                                ]
                            })(
                                <Input placeholder="请输入角色" type="text"/>
                            )
                    }
                </Form.Item>
                <Form.Item label="描述" {...formItemLayout}>
                    {
                        roleInfo && type ==='detail' ? roleInfo.remark:
                            getFieldDecorator('remark',{
                                initialValue:roleInfo.remark,
                            })(
                                <Input  type="text"/>
                            )
                    }
                </Form.Item>
            </Form>
        )
    }
}
RoleForm = Form.create({})(RoleForm)